package com.logisticsinquiry.android.logic



import android.util.Log
import androidx.lifecycle.liveData
import com.logisticsinquiry.android.logic.network.KdniaoTrackQueryAPI
import kotlinx.coroutines.Dispatchers
import java.lang.RuntimeException
import kotlin.coroutines.CoroutineContext

object Repository {
    val api = KdniaoTrackQueryAPI()

    //返回快递的物流轨迹
    fun expressQuery(logisticCode: String) = fire(Dispatchers.IO) {
        val shipperCode = api.searchShipper(logisticCode).Shippers[0].ShipperCode
        val expressQueryResponse = api.expressQuery(shipperCode,logisticCode)
        Log.d("调试信息",expressQueryResponse.toString())
        if (expressQueryResponse.Success == true) {
            val traces = expressQueryResponse.Traces
            Result.success(traces)
        } else {
            Result.failure(RuntimeException("response status is ${expressQueryResponse.Success}"))
        }
    }
    //返回可能属于的品牌编号及名称数组
    fun searchShipper(logisticCode: String) = fire(Dispatchers.IO) {
        Log.v("调试信息，是否成功调用Repository","yes")
        val result = api.searchShipper(logisticCode)
        if (result.Success == true) {
            Log.v("进入API，调用方法结束","yes")
            val shipper = api.searchShipper(logisticCode)
            Result.success(shipper)
        } else {
            Log.v("调试信息网络层","faliure")
            Result.failure(RuntimeException("response status is ${result.Success}"))
        }
    }

    private fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) =
        liveData<Result<T>>(context) {
            val result = try {
                block()
            } catch (e: Exception) {
                Result.failure<T>(e)
            }
            emit(result)
        }
}